﻿using BLL;
using Microsoft.AspNet.Identity;
using Models;
using Inspinia_MVC5.Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Inspinia_MVC5.Controllers
{
    [AllowCors]
    public class LoginController : Controller
    {
        // GET: Login登录功能
        public ActionResult Index(string returnUrl)
        {
            string name = Request.Form["Username"];
            string password = Request.Form["Password"];
            string validate = Request.Form["Validate"];
            string phonevalid = Request.Form["PhoneValid"];
            if (Session["ValidateCode"].ToString() != validate)
            {
                return RedirectToAction("LoginZh", "Login", new { message = "验证码错误！" });
            }
            //if(phonevalid != "9999")
            //{
            //    return RedirectToAction("LoginZh", "Login", new { message = "短信验证码错误！" });
            //}
            PassswordHash x = new PassswordHash();
            AspNetUsersService AspNetUsersService = new AspNetUsersService();
            AspNetUsers aspnetuser = AspNetUsersService.Find(u => u.UserName == name);
            if (aspnetuser == null) 
            {
                return Redirect("/Warn/NoUser");
            }
            string result = x.VerifyHashedPassword(aspnetuser.PasswordHash,password).ToString();
            if ( result == "Success" )
            {
                if (Session["username"] == null)
                {
                    Session["username"] = name;
                    Session["userid"] = aspnetuser.Id;
                    Session["identity"] = aspnetuser.AspNetRoles.First().Name;
                    if (aspnetuser.AspNetRoles.First().Name != "Admin")
                    {
                        Session["wellstr"] = OwnWell(name);
                        Session["blockstr"] = OwnBlock(name);
                    }
                    else
                    {
                        Session["wellstr"] = "0";
                        Session["blockstr"] = "0";
                    }
                }
                if (returnUrl == null)
                    returnUrl = "/WellList/Index";
                return Redirect(returnUrl);
            }
            else
            {
                return Redirect("/Warn/WrongUser");
            }
        }
        //注销功能
        [SessionTimeOutFilter]
        public ActionResult Logout()
        {
            if (Session["username"] != null)
            {
                Session.RemoveAll();
                //return Redirect("/Login/LoginZh");
                return Redirect("/Login/LoginEn");
            }
            return Redirect("/Login/WrongUser");
        }
        //判断是否登录功能
        [SessionTimeOutFilter]
        public JsonResult IsLogin()
        {
            string username = Session["username"].ToString();
            string identity = Session["identity"].ToString();
            return Json(new { status = "0", name = username, identity = identity }, JsonRequestBehavior.AllowGet);
        }
        //获得个人所拥有井的字符串
        public string OwnWell(String name)
        {
            string wellstr = "";
            AspNetUsersService AspNetUsersService = new AspNetUsersService();
            User2WellService User2WellService = new User2WellService();
            AspNetUsers aspnetuser = AspNetUsersService.Find(u => u.UserName == name);
            var wells = User2WellService.All().Where(c => c.UserId == aspnetuser.Id);
            wellstr += "-";
            foreach(var well in wells)
            {
                wellstr += well.Well.ID;
                wellstr += "-";
            }
            return wellstr;
        }
        //获得个人所拥有区块的字符串
        public string OwnBlock(String name)
        {
            string blockstr = "";
            AspNetUsersService AspNetUsersService = new AspNetUsersService();
            User2WellService User2WellService = new User2WellService();
            WellService WellService = new WellService();
            AspNetUsers aspnetuser = AspNetUsersService.Find(u => u.UserName == name);
            var wells = User2WellService.All().Where(c => c.UserId == aspnetuser.Id);
            blockstr += "-";
            foreach (var well in wells)
            {
                blockstr += WellService.Find(c=>c.ID==well.Well.ID).BLOCK_ID;
                blockstr += "-";
            }
            return blockstr;
        }
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
        public JsonResult Test()
        {
            return Json(new { status = Request.ServerVariables.Get("Local_Addr").ToString(), status1 = Request.ServerVariables["SERVER_PORT"].ToString() }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult LoginOld()
        {
            return View();
        }
        public ActionResult LoginZh()
        {
            
            return View();
        }
        public ActionResult LoginEn()
        {
            return View();
        }
    }
}